package cn.tanghom.app.system.controller;

import java.util.LinkedList;
import java.util.List;

import cn.tanghom.app.system.model.User;
import cn.tanghom.conf.CommonKey;
import cn.tanghom.support.utils.CommonUtils;
import cn.tanghom.support.utils.StringUtils;
import cn.tanghom.support.websocket.MsgPublisher;
import cn.tanghom.support.websocket.SystemWebSocketHandler;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.WebSocketSession;

import static cn.tanghom.support.web.BaseController.THEME_PATH;


/**
 * 描述
 *
 * @author tanghom<tanghom@qq.com> on 2016/7/7
 */
@Controller
@RequestMapping(value="msg")
public class MessageController {

    /**
     * notify
     *
     * @return
     */
    @RequestMapping(value = "notify", method = RequestMethod.GET)
    public String notifyMsg() {
        return THEME_PATH + "/system/msg/notify";
    }

    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    @ResponseBody
    public String sendAll(String msg) {
        try {
            if(StringUtils.isNullOrEmpty(msg)){
                return CommonUtils.msgCallback(false, "发送失败,请填写内容", "", null);
            }
            MsgPublisher.getInstance().publish("系统通知", msg);
            return CommonUtils.msgCallback(true, "发送成功", "", null);
        } catch (Exception e) {
            return CommonUtils.msgCallback(false, "发送失败", "", null);
        }
    }
    /**未读消息数*/
    @RequestMapping(value = "unread", method = RequestMethod.GET)
    @ResponseBody
    public Integer unread() {
    	SystemWebSocketHandler handler = new SystemWebSocketHandler();
    	Subject currentUser = SecurityUtils.getSubject();
        String loginName = (String)currentUser.getPrincipal();        
        WebSocketSession sess = handler.session(loginName);
        if(sess==null) return null;
        List<String> list = (List<String>) sess.getAttributes().get("messages");
		if(list==null){
			return 0;
		}
        return list.size();
    }
}
